/*
 * Dijjer - A Peer to Peer HTTP Cache
 * Copyright (C) 2004,2005 Change.Tv, Inc
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package dijjer.util;

import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5OutputStream extends OutputStream {

	private static final String[] HEX_DIGITS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
			"e", "f"};
	OutputStream _wrapped;
	private MessageDigest _md;
	
	public MD5OutputStream(OutputStream wrapped) {
		super();
		_wrapped = wrapped;
		try {
			_md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	public void write(byte[] bytes, int start, int length) throws IOException {
		_md.update(bytes, start, length);
		_wrapped.write(bytes, start, length);
	}

	public void write(byte[] bytes) throws IOException {
		_md.update(bytes);
		_wrapped.write(bytes);
	}
	
	public void write(int b) throws IOException {
		_md.update((byte) b);
		_wrapped.write(b);
	}

	public void flush() throws IOException {
		_wrapped.flush();
	}
	
	public void close() throws IOException {
		_wrapped.close();
	}
	
	public String getMD5Sum() {
		return bytes2Hex(_md.digest());
	}
	
	private static String byte2Hex(byte b) {
		int nb = b & 0xFF;
		int i_1 = (nb >> 4) & 0xF;
		int i_2 = nb & 0xF;
		return HEX_DIGITS[i_1] + HEX_DIGITS[i_2];
	}

	private static String bytes2Hex(byte[] b) {
		StringBuffer sb = new StringBuffer(b.length * 2);
		for (int x = 0; x < b.length; x++) {
			sb.append(byte2Hex(b[x]));
		}
		return sb.toString();
	}
}
